package com.ymatou.apigateway.testcase;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.bean.GetCurrencyConfigBean;
import com.shop2cn.iapi.shenqisettlement.parameter.resp.GetCurrencyConfigResp;
import com.shop2cn.iapi.shenqisettlement.service.GetCurrencyConfigCall;
import com.ymatou.apigateway.parameter.AesUtil;
import com.ymatou.apigateway.parameter.OpenapiReq;
import com.ymatou.apigateway.parameter.SqAddProductBean;
import com.ymatou.apigateway.parameter.SqAgentPriceDto;
import com.ymatou.apigateway.parameter.SqCatalogDto;
import com.ymatou.apigateway.parameter.SqCatalogPropDto;
import com.ymatou.apigateway.parameter.SqSubCodeDto;
import com.ymatou.apigateway.service.OpenapiService;
import com.ymatou.apigateway.service.ShenqiAddProductCall;
import com.shop2cn.iapi.agentproducts.parameter.AgentPricePo;
import com.ymatou.iapi.godmch.parameter.AgentTypeVo;
import com.ymatou.iapi.godmch.parameter.listagentTypeBean;
import com.ymatou.iapi.prodstock.parameter.AgentProductPo;
import com.ymatou.mq.admin.parameter.MessageListBean;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.AddAgentProductCallService;
import com.ymttest.business.service.AssertService;
import com.ymttest.business.service.MqQueryCallService;
import com.ymttest.business.service.shenqi.GodmchManageCallService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.annotation.SqlMapperFactory;
import com.ymttest.database.annotation.product.IntergratedProductMapper;
import com.ymttest.database.model.Application;
import com.ymttest.database.model.AuthCode;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.model.mch_info;
import com.ymttest.database.model.godmch.mch_depot_info;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.CatalogsWapper;
import com.ymttest.database.sqlwapper.OpenApiWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.database.sqlwapper.godmch.DefGodMchWapper;
import com.ymttest.database.sqlwapper.godmch.mch_infoWapper;
import com.ymttest.utils.AgentUsers;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

/**
 * 更新商品库存 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_sqAddProduct {

	private static OpenapiReq openapiReq;

	private static SqAddProductBean sqAddProductBean;
	private static ShenqiAddProductCall shenqiAddProductCall;

	private static IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();

	private static YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
	private static YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();

	private static mch_infoWapper infoWapper = new mch_infoWapper();

	// vip渠道
	private static int vipRootUserId = AgentUsers.vipRootUserId;
	private static String vipRootUserName = "NickautoTest";
	
	private static long multiCDFCodeGoodsOwnerId = ShenqiUserSet.multiCDFCodeGoodsOwnerId;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("添加神器商品");
	}

	@Before
	public void caseUp() {
		openapiReq = new OpenapiReq();
		openapiReq.setMethod("sq.product.add");

		sqAddProductBean = new SqAddProductBean();
		shenqiAddProductCall = new ShenqiAddProductCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(shenqiAddProductCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	public static SqAddProductBean initAddProduct(int sellerId, String sellerName, boolean setAgentPrice) throws ClientProtocolException, IOException {

		SqAddProductBean addproductBean = new SqAddProductBean();
		// 税率
		addproductBean.setTariff_rate(9.1);
		addproductBean.setUser_id(sellerId);
		addproductBean.setUser_name(sellerName);
		// 发布类型 1-发布上架 2-保存为下架
		addproductBean.setSale_type(1);
		addproductBean.setSet_agent_price(setAgentPrice);
		// 标题
		addproductBean.setTitle("God" + TestDataManager.getRandomNum(6));
		addproductBean.setMarket_currency("USD");
		
		addproductBean.setProduct_code("货号" + TestDataManager.getRandomNum(6));

		List<String> picList = new ArrayList<>();
		picList.add("http://pic1.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701_400_401_n_w_l.jpg");
		picList.add("http://pic1.shop2cn.com/G01/M00/41/2B/rBBlD1yYU-SAJhweAADmTO2YrBw085_1_1_o.jpg");
		picList.add("http://pic1.shop2cn.com/G01/M00/40/C9/rBBlD1yYTCmAZV4MAAFgY-30kgs700_1_1_o.jpg");
		// 商品图片
		addproductBean.setMain_pic_list(picList);
		// 规格列表1
		SqCatalogDto catalogDto = new SqCatalogDto();
		// 直销价
		catalogDto.setDirect_price(900d);
		// catalogDto.setDirectPrice(1d);

		catalogDto.setMarket_price(10d);
		catalogDto.setCounter_price(1d);
		
		catalogDto.setCost_price(24.21d);

		// 库存
		catalogDto.setStock(100);
		catalogDto.setWeight(3);
		catalogDto.setPic("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701_400_401.jpg");
		String sku1 = TestDataManager.getRandomNum(6);
		String sku2 = TestDataManager.getRandomNum(6);
		// 商户商品编码
		catalogDto.setSku_id(sku1);
		// 规格名称
		catalogDto.setProperty_value("God商品" + TestDataManager.getRandomNum(10));// 已经没用
		List<SqAgentPriceDto> agentPriceDtos = new ArrayList<>();
		catalogDto.setAgent_price_list(agentPriceDtos);

		SqCatalogPropDto catalogPropDto1 = new SqCatalogPropDto();
		catalogPropDto1.setName("自动化测试1_" + TestDataManager.getRandomNum(5));
		catalogPropDto1.setPic("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701.jpg");
		catalogPropDto1.setSub_type("欧码");
		catalogPropDto1.setValue("170");

		SqCatalogPropDto catalogPropDto2 = new SqCatalogPropDto();
		catalogPropDto2.setName("自动化测试2_" + TestDataManager.getRandomNum(5));
		catalogPropDto2.setPic("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701.jpg");
		catalogPropDto2.setSub_type("国码");
		catalogPropDto2.setValue("180");

		SqCatalogPropDto catalogPropDto3 = new SqCatalogPropDto();
		catalogPropDto3.setName("自动化测试3_" + TestDataManager.getRandomNum(5));
		catalogPropDto3.setPic("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701.jpg");
		catalogPropDto3.setSub_type("美码");
		catalogPropDto3.setValue("190");

		SqCatalogPropDto catalogPropDto4 = new SqCatalogPropDto();
		catalogPropDto4.setName("自动化测试4_" + TestDataManager.getRandomNum(5));
		catalogPropDto4.setPic("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701.jpg");
		catalogPropDto4.setSub_type("日码");
		catalogPropDto4.setValue("160");

		List<SqCatalogPropDto> propertyList1 = new ArrayList<>();
		List<SqCatalogPropDto> propertyList2 = new ArrayList<>();

		propertyList1.add(catalogPropDto1);
		propertyList1.add(catalogPropDto2);
		propertyList2.add(catalogPropDto3);
		propertyList2.add(catalogPropDto4);
		catalogDto.setProperty_list(propertyList1);
		// 规格列表2
		SqCatalogDto CatalogDto = new SqCatalogDto();
		CatalogDto.setDirect_price(900d);
		// CatalogDto.setDirectPrice(1d);
		CatalogDto.setStock(100);
		CatalogDto.setSku_id(sku2);
		CatalogDto.setWeight(1);
		CatalogDto.setPic("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701_401.jpg");
		CatalogDto.setProperty_value("God商品" + TestDataManager.getRandomNum(10));
		CatalogDto.setAgent_price_list(agentPriceDtos);

		CatalogDto.setProperty_list(propertyList2);

		List<SqCatalogDto> catalogDtos = new ArrayList<>();
		catalogDtos.add(catalogDto);
		catalogDtos.add(CatalogDto);
		
		// 一品多码商品商户添加子码
		if (sellerId == multiCDFCodeGoodsOwnerId) {

			catalogDtos.forEach(p -> {

				List<SqSubCodeDto> subCodeList = new ArrayList<>();

				SqSubCodeDto sqSubCodeDto1 = new SqSubCodeDto();

				sqSubCodeDto1.setCode(TestDataManager.getRandomUUID()
						.toString());
				sqSubCodeDto1.setAttr("subCodettr"
						+ TestDataManager.randomStr(5));
				sqSubCodeDto1.setEffective_period("2030-04-09");
				// catalogSubCodeDto1.setEffectivePeriod(TestDataManager.getRandomNum(4)
				// + "-04-09");
					sqSubCodeDto1.setStock(100);
					sqSubCodeDto1.setBanned(true);

					SqSubCodeDto sqSubCodeDto2 = new SqSubCodeDto();

					sqSubCodeDto2.setCode(TestDataManager.getRandomUUID()
							.toString());
					sqSubCodeDto2.setAttr("subCodettr"
							+ TestDataManager.randomStr(5));
					sqSubCodeDto2.setEffective_period("2029-04-09");
					// catalogSubCodeDto2.setEffectivePeriod(TestDataManager.getRandomNum(4)
					// + "-04-09");
					sqSubCodeDto2.setStock(100);

					subCodeList.add(sqSubCodeDto1);
					subCodeList.add(sqSubCodeDto2);

					p.setSub_code_list(subCodeList);
				});
		}

		if (setAgentPrice) {
			listagentTypeBean listagentTypeBean = GodmchManageCallService.InitlistgentTypeBean(sellerId);
			List<AgentTypeVo> agentTypeVos = GodmchManageCallService.listgentTypeCall(listagentTypeBean).getAgentTypes();
			catalogDtos.forEach(p -> {
				List<SqAgentPriceDto> agentPriceDtos1 = new ArrayList<>();
				agentTypeVos.forEach(x -> {
					if (x.getAgentType() != 0) {
						SqAgentPriceDto agentPriceDto = new SqAgentPriceDto();
						// agentPriceDto.setAgentTypeId(x.getAgentType());
						agentPriceDto.setAgent_type_name(x.getTitle());
						double price = Double.parseDouble(1 + TestDataManager.getRandomNum(2));
						agentPriceDto.setAgent_price(price);
						agentPriceDtos1.add(agentPriceDto);
					}
				});
				p.setAgent_price_list(agentPriceDtos1);
			});
		}
		addproductBean.setCatalog_list(catalogDtos);
		addproductBean.setDeliver_type(999);
		addproductBean.setCard_info(0);
		addproductBean.setCategory_id(1002);
		addproductBean.setThird_category_id(1003);
		addproductBean.setBrand_id(AddAgentProductCallService.BrandId);
		addproductBean.setRemark("测试商品");
		addproductBean.setCurrency("USD");
		addproductBean.setDescription("ceshishangping");
		addproductBean.setDesc_pic_list(Arrays.asList("http://pc1.img.shop2cn.com/G01/shangou/M00/2C/D0/rBBlD1gHOV6AY32AAAEN6UG5TOc701_400_401_n_w_l.jpg"));
		// 是否在买家端店铺首页中不可见 false 可见
		addproductBean.setInvisible(false);
		// addproductBean.setFreight_template_name("0");

		return addproductBean;
	}

	/**
	 * 根据国家获取币种详情
	 * 
	 * @param currency
	 * @return
	 * @throws IOException
	 */
	public static GetCurrencyConfigResp getCurrencyConfigResp(String currency) throws IOException {
		GetCurrencyConfigBean getcurrencyconfigBean = new GetCurrencyConfigBean();
		GetCurrencyConfigCall getcurrencyconfigCall = new GetCurrencyConfigCall();
		getcurrencyconfigBean.setCurrency(currency);
		getcurrencyconfigCall.setData(getcurrencyconfigBean);
		getcurrencyconfigCall.callService();
		return getcurrencyconfigCall.getCurrencyConfigResp();
	}

	@SuppressWarnings("rawtypes")
	public void verifyMongoCurMq(String pid) throws IOException, InterruptedException {
		Thread.sleep(1000);
		MessageListBean MessageListBean2 = MqQueryCallService.initAgentMongoCrud(pid);
		List<Map> joa2 = MqQueryCallService.GetMqMessage(MessageListBean2);
		Logger.debug(joa2);
		String actionType = "AddAgentProduct";
		String appId = "agentproducts.iapi.shop2cn.com";
		Logger.verifyEquals(actionType, joa2.get(0).get("ActionType"), "验证ActionType");
		Logger.verifyEquals(pid, joa2.get(0).get("ProductId"), "验证ProductId");
		Logger.verifyEquals(appId, joa2.get(0).get("AppId"), "验证AppId");
	}

	@SuppressWarnings("rawtypes")
	public static void checkAddAgentProduct(String productId, SqAddProductBean agentProductBean, boolean isCsId) throws Exception {
		Map<String, Object> pmap = ipm.selectProductByProdId(productId);
		// check product
		Logger.comment("验证product：" + productId);
		int sellerId = 0;
		if (isCsId) {
			sellerId = Integer.parseInt(new DefGodMchWapper().selectCsInfoByCsId(agentProductBean.getUser_id()).get(0).get("mchId").toString());
		} else {
			sellerId = agentProductBean.getUser_id();
		}
		Logger.verifyEquals(sellerId, Integer.parseInt(pmap.get("iUserId").toString()), "验证SellerId");
		Logger.verifyEquals(agentProductBean.getTitle(), pmap.get("sProduct").toString(), "验证productName");
		Logger.verifyEquals(agentProductBean.getDeliver_type(), Integer.parseInt(pmap.get("iCatalogStatus").toString()), "验证商品物流类型");
		if (agentProductBean.getDeliver_type() == 999) {
			Logger.verifyEquals(0, Integer.parseInt(pmap.get("CardInfo").toString()), "验证商品物流方式中身份信息是否提供");
		} else if (agentProductBean.getDeliver_type() == 100 && agentProductBean.getCard_info() == 1) {
			Logger.verifyEquals(1, Integer.parseInt(pmap.get("CardInfo").toString()), "验证商品物流方式中身份信息是否提供");
		} else if (agentProductBean.getDeliver_type() == 0) {
			Logger.verifyEquals(0, Integer.parseInt(pmap.get("CardInfo").toString()), "验证商品物流方式中身份信息是否提供");
		} else if (agentProductBean.getDeliver_type() == 4) {
			Logger.verifyNotEquals(2, Integer.parseInt(pmap.get("CardInfo").toString()), "验证商品物流方式中身份信息是否提供");
		} else {
			Logger.verifyEquals(2, Integer.parseInt(pmap.get("CardInfo").toString()), "验证商品物流方式中身份信息是否提供");
		}
		Logger.verifyEquals(agentProductBean.getCategory_id() == 0 ? 0 : agentProductBean.getCategory_id(), Integer.parseInt(pmap.get("iCategoryId").toString()), "验证二级类目编号");
		Logger.verifyEquals(agentProductBean.getThird_category_id() == 0 ? 0 : agentProductBean.getThird_category_id(), Integer.parseInt(pmap.get("iThirdCategoryId").toString()),
				"验证商品三级类目编号");
		Logger.verifyEquals(agentProductBean.getBrand_id(), Integer.parseInt(pmap.get("iBrandId").toString()), "验证品牌编号");
		Logger.verifyEquals(agentProductBean.getRemark(), pmap.get("Remark").toString(), "验证商品描述");
		Logger.verifyEquals(agentProductBean.getMain_pic_list().get(0), pmap.get("sPicUrl").toString(), "验证商品主图（首图）");
		// Logger.verifyEquals(0,
		// Integer.parseInt(pmap.get("iAction").toString()), "验证action");
		Logger.verifyEquals(3, Integer.parseInt(pmap.get("ProductType").toString()), "验证商品类型");

		AssertService.assertTime(YMTDateUtil.getDate(), (Date) pmap.get("dAddTime"), 120, "验证商品发布时间");
		AssertService.assertTime(YMTDateUtil.getDate(), (Date) pmap.get("dLastUpdate"), 120, "验证商品最后更新时间");

		GetCurrencyConfigResp currencyConfigResp = getCurrencyConfigResp(agentProductBean.getCurrency());
		Logger.verifyEquals(agentProductBean.getCurrency(), currencyConfigResp.getCurrency(), "验证currency");

		List<Map<String, Object>> maps = ipm.selectDescConfigPictureByProdIdAndSellerId(productId, sellerId);

		String pictureUrl = maps.stream().map(x -> x.get("PictureUrl").toString()).collect(Collectors.toList()).toString();
		agentProductBean.getDesc_pic_list().forEach(p -> {
			Logger.verifyEquals(true, pictureUrl.contains(p), "验证DescPicList");
		});
		String maps1 = ipm.selectDescConfigWordByProdIdAndSellerId(productId, sellerId).stream().map(x -> x.get("WordContent").toString()).collect(Collectors.toList()).toString();
		Logger.verifyEquals(true, maps1.contains(agentProductBean.getDescription()), "验证Description");

		// check pic
		List<Map<String, Object>> pictures = ipm.selectPictureByProdIdAndAction0(productId);
		for (int i = 0; i < agentProductBean.getMain_pic_list().size(); i++) {
			Logger.comment("验证pictures");
			Logger.verifyEquals(agentProductBean.getMain_pic_list().get(i), pictures.get(i).get("sOriUrl").toString(), "验证商品图片地址");
			Logger.verifyEquals(true, Integer.parseInt(pictures.get(i).get("iAction").toString()) > -1, "验证商品图片有效");
			AssertService.assertTime(YMTDateUtil.getDate(), (Date) pictures.get(i).get("dAddTime"), 120, "验证商品图片的添加时间");
		}

		// check catalog
		List<YmtCatalogsI> ymtCatalogsIList = ymtCatalogsIWapper.selectCatalogsByProductId(productId);
		agentProductBean.getCatalog_list().forEach(p -> {
			for (YmtCatalogsI ymtCatalogsI : ymtCatalogsIList) {
				// check Ymt_CatalogSetAttributes
				if (ymtCatalogsI.getsSKU().equals(p.getSku_id())) {
					Logger.comment("验证规格");
					Logger.verifyEquals(p.getDirect_price(), ymtCatalogsI.getfQuotePrice().doubleValue(), "验证直销价");
					DataUtil.verifyDecimalEquals(p.getCost_price(), ymtCatalogsI.getCostPrice().doubleValue(), "验证成本价");
					System.out.println(p.toString());
					System.out.println(ymtCatalogsI.toString());
					Logger.verifyEquals(p.getStock(), ymtCatalogsI.getiNum(), "验证总库存");
					Logger.verifyEquals(p.getVirtual_stock(), ymtCatalogsI.getVirtualStock(), "验证虚拟库存");

					if (ymtCatalogsI.getiNum() == 0 || ymtCatalogsI.getfQuotePrice().doubleValue() == 0.0) {
						Logger.verifyEquals(-2, ymtCatalogsI.getiAction(), "验证action");
					} else {
						Logger.verifyEquals(0, ymtCatalogsI.getiAction(), "验证action");
					}
					Logger.verifyEquals(p.getSku_id(), ymtCatalogsI.getsSKU(), "验证sku");
					Logger.verifyEquals(p.getPic(), ymtCatalogsI.getsPicUrl(), "验证pic");
					Logger.verifyEquals(p.getWeight(), ymtCatalogsI.getWeight().doubleValue(), "验证Weight");
					AssertService.assertTime(YMTDateUtil.getDate(), (Date) ymtCatalogsI.getdAddTime(), 120, "验证商品规格的发布时间");
					// if (p.getMarket_price() != null) {
					//
					// Logger.verifyEquals(
					// p.getMarket_price(),
					// ymtCatalogsI.getMarketPrice().doubleValue(),
					// "验证市场价");
					// }
					//
					// if (p.getCounter_price() != null) {
					//
					// Logger.verifyEquals(
					// p.getCounter_price(),
					// ymtCatalogsI.getMarketAmount(),
					// "验证折扣价");
					// }
				}
				// 验证规格属性
				List<Map<String, Object>> map = ipm.selectCatalogProAndValByCatalogId(ymtCatalogsI.getsCatalogId());
				map.forEach(x -> {
					p.getProperty_list().forEach(o -> {
						if (o.getValue().equals(x.get("sCategoryAttribute").toString())) {
							Logger.verifyEquals(o.getName(), x.get("sProductProperty").toString(), "验证name");
							Logger.verifyEquals(o.getPic(), x.get("sPicUrl").toString(), "验证pic");
							Logger.verifyEquals(o.getSub_type(), x.get("SubType").toString(), "验证SubType");
						}
					});
				});

				// check ymt_AgentPrice
				if (agentProductBean.isSet_agent_price()) {
					p.getAgent_price_list().forEach(x -> {
						List<AgentPricePo> agentPricePos = ymtProductsIWapper.selectAgentPriceByCatalogId(ymtCatalogsI.getsCatalogId(), x.getAgent_type_id());
						agentPricePos.forEach(c -> {
							if (x.getAgent_price() == c.getAgentPrice()) {
								Logger.comment("验证代理价格");
								Logger.verifyEquals(x.getAgent_type_id(), c.getAgentTypeId(), "验证代理价格");
								Logger.verifyEquals(productId, c.getProductId(), "验证productId");
								AssertService.assertTime(YMTDateUtil.getDate(), (Date) c.getCreateTime(), 120, "验证创建时间");
								AssertService.assertTime(YMTDateUtil.getDate(), (Date) c.getUpdateTime(), 120, "验证更新时间");
							}
						});
					});
				}
			}
		});
		// check AgentProducts
		AgentProductPo agentProductPo = ymtProductsIWapper.selectAgentProductByProductId(productId);
		Logger.comment("验证AgentProducts");
		Logger.verifyEquals(sellerId, agentProductPo.getUserId(), "验证UserId");
		Logger.verifyEquals(0, agentProductPo.getAgentType(), "验证代理类型");
		Logger.verifyEquals(agentProductBean.isInvisible(), agentProductPo.isInvisible(), "验证Invisible");
		Logger.verifyEquals(agentProductBean.isSet_agent_price(), agentProductPo.isSetAgentPrice(), "验证是否允许下级代理");
		if (agentProductBean.getSale_type() == 2) {
			Logger.verifyEquals(2, agentProductPo.getStatus(), "验证商品是下架状态");
		} else {
			Logger.verifyEquals(1, agentProductPo.getStatus(), "验证商品是上架状态");
		}
		// Logger.verifyEquals(0, agentProductPo.getAction(), "验证商品action");
		Logger.verifyEquals(0, agentProductPo.getParentUserId(), "验证商品parentUserId");
		Logger.verifyEquals(null, agentProductPo.getParentProductId(), "验证商品parentProductId");
		Logger.verifyEquals(sellerId, agentProductPo.getRootUserId(), "验证商品parentProductId");
		Logger.verifyEquals(productId, agentProductPo.getRootProductId(), "验证商品rootProductId");
		mch_info minfo = infoWapper.selectby(MapUtil.hashMap("mchId", sellerId)).get(0);
		Logger.verifyEquals(true, agentProductPo.getAgentChain().contains(minfo.getSeqId().toString()), "验证AgentChain");
		Logger.verifyEquals(0, agentProductPo.getAgentType(), "验证agentType");
		AssertService.assertTime(YMTDateUtil.getDate(), (Date) agentProductPo.getCreateTime(), 120, "验证创建时间");
		AssertService.assertTime(YMTDateUtil.getDate(), (Date) agentProductPo.getUpdateTime(), 120, "验证更新时间");

		// check Ymt_AgentWxCodePic
//		Thread.sleep(2000);
//		Map map = ymtProductsIWapper.selectAgentWxCodePicByProductId(productId).get(0);
//		Logger.verifyEquals(agentProductPo.getUserId(), Integer.parseInt(map.get("UserId").toString()), "验证UserId");
		// Logger.verifyEquals(1,
		// Integer.parseInt(map.get("Action").toString()), "验证Action");

		// check Ymt_ProductDeliveryTemplate
		if (agentProductBean.getFreight_template_name() != null && agentProductBean.getFreight_template_name().equalsIgnoreCase("0")) {
			Map deliMap = ymtProductsIWapper.getProductDeliveryTemplateByProdId(productId).get(0);
			Logger.debug("deliMap:" + deliMap);
			Logger.verifyEquals(agentProductBean.getUser_id(), Integer.parseInt(deliMap.get("SellerId").toString()), "验证sellerId");
			Logger.verifyEquals(agentProductBean.getFreight_template_name(), Integer.parseInt(deliMap.get("TemplateId").toString()), "验证TemplateId");
			Logger.verifyEquals(agentProductBean.getDeliver_type(), Integer.parseInt(deliMap.get("CatalogStatus").toString()), "验证CatalogStatus");
			Logger.verifyEquals(1, Integer.parseInt(deliMap.get("Status").toString()), "验证Status");
			Logger.verifyEquals(productId, deliMap.get("ProductId").toString(), "验证ProductId");
		}
	}

	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_sqAddProduct_001() {
		Logger.start(true, "添加神器商品");
		try {

			// long sellerId = 500004881l;

			sqAddProductBean = initAddProduct(vipRootUserId, vipRootUserName, true);

			// 商户商品编码
			sqAddProductBean.getCatalog_list().forEach(c -> {
				String sku1 = TestDataManager.getRandomNum(6);
				c.setSku_id(sku1);
				c.setOuter_sku_id(null);
				//设置了专柜价格没写币种会报错
				c.setCounter_price(null);
			});
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper.selectApplicationBySellerId((long) vipRootUserId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id).get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil().beanToGSONString(sqAddProductBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq, AesUtil.decrypt(app_secret)));

			String url = String.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.product.add", app_id);
			shenqiAddProductCall.setUrl(url);

			shenqiAddProductCall.setData(openapiReq);
			shenqiAddProductCall.callService();

			JSONObject retBean = new JSONObject(shenqiAddProductCall.getReturnData());

			Logger.verifyEquals("0000", shenqiAddProductCall.getCode(), "验证Code");

			String productId = retBean.getJSONObject("content").getString("product_id");

			Thread.sleep(2000);

			// 验证数据库
			checkAddAgentProduct(productId, sqAddProductBean, false);
			verifyMongoCurMq(productId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_sqAddProduct_002() {
		Logger.start(true, "添加神器商品-修改字段outerskuid");
		try {

			// long sellerId = 500004881l;

			sqAddProductBean = initAddProduct(vipRootUserId, vipRootUserName, true);
			// 商户商品编码
			sqAddProductBean.getCatalog_list().forEach(c -> {
				String sku1 = TestDataManager.getRandomNum(6);
				c.setSku_id(null);
				c.setOuter_sku_id(sku1);
				c.setCounter_price(null);
			});
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper.selectApplicationBySellerId((long) vipRootUserId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id).get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil().beanToGSONString(sqAddProductBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq, AesUtil.decrypt(app_secret)));

			String url = String.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.product.add", app_id);
			shenqiAddProductCall.setUrl(url);

			shenqiAddProductCall.setData(openapiReq);
			shenqiAddProductCall.callService();

			JSONObject retBean = new JSONObject(shenqiAddProductCall.getReturnData());

			Logger.verifyEquals("0000", shenqiAddProductCall.getCode(), "验证Code");

			String productId = retBean.getJSONObject("content").getString("product_id");

			Thread.sleep(2000);

			// 验证数据库
			checkAddAgentProduct(productId, sqAddProductBean, false);
			verifyMongoCurMq(productId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_sqAddProduct_003() {
		Logger.start(true, "添加神器商品-设置专柜价币种");
		try {

			// long sellerId = 500004881l;

			sqAddProductBean = initAddProduct(vipRootUserId, vipRootUserName, true);
			// 商户商品编码
			sqAddProductBean.setCounter_currency("CNY");
			sqAddProductBean.getCatalog_list().forEach(c -> {
				String sku1 = TestDataManager.getRandomNum(6);
				c.setSku_id(null);
				c.setOuter_sku_id(sku1);
				c.setCounter_price(10d);
			});
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper.selectApplicationBySellerId((long) vipRootUserId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id).get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil().beanToGSONString(sqAddProductBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq, AesUtil.decrypt(app_secret)));

			String url = String.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.product.add", app_id);
			shenqiAddProductCall.setUrl(url);

			shenqiAddProductCall.setData(openapiReq);
			shenqiAddProductCall.callService();

			JSONObject retBean = new JSONObject(shenqiAddProductCall.getReturnData());

			Logger.verifyEquals("0000", shenqiAddProductCall.getCode(), "验证Code");

			String productId = retBean.getJSONObject("content").getString("product_id");

			Thread.sleep(2000);

			// 验证数据库
			checkAddAgentProduct(productId, sqAddProductBean, false);
			verifyMongoCurMq(productId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_sqAddProduct_004() {
		Logger.start(true, "添加神器商品-新增字段depot_name-分仓");
		try {

			// long sellerId = 500004881l;
			List<mch_depot_info> depotList = GodmchManageCallService
                    .SelectDepotByMchId(vipRootUserId);
    
			sqAddProductBean = initAddProduct(vipRootUserId, vipRootUserName, true);
			sqAddProductBean.setDepot_name(depotList.get(0).getDepotTitle());
			Integer depotid=depotList.get(0).getDepotId();
			// 商户商品编码
			sqAddProductBean.getCatalog_list().forEach(c -> {
				String sku1 = TestDataManager.getRandomNum(6);
				c.setSku_id(sku1);
				c.setOuter_sku_id(null);
				//设置了专柜价格没写币种会报错
				c.setCounter_price(null);
			});
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper.selectApplicationBySellerId((long) vipRootUserId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id).get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil().beanToGSONString(sqAddProductBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq, AesUtil.decrypt(app_secret)));

			String url = String.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.product.add", app_id);
			shenqiAddProductCall.setUrl(url);

			shenqiAddProductCall.setData(openapiReq);
			shenqiAddProductCall.callService();

			JSONObject retBean = new JSONObject(shenqiAddProductCall.getReturnData());

			Logger.verifyEquals("0000", shenqiAddProductCall.getCode(), "验证Code");

			String productId = retBean.getJSONObject("content").getString("product_id");

			Thread.sleep(2000);

			// 验证数据库
//			checkAddAgentProduct(productId, sqAddProductBean, false);
			Map<String, Object> pmap = ipm.selectProductByProdId(productId);
			Logger.debug(depotid+":"+pmap.toString());
			Logger.verifyEquals(new BigDecimal(depotid).setScale(0), new BigDecimal( pmap.get("iBondedArea").toString()).setScale(0), "验证分仓");
//			verifyMongoCurMq(productId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_sqAddProduct_005() {
		Logger.start(true, "添加神器商品-新增字段productParam");
		try {
			//有白名单需要特定商户
//			 Long sellerId = AgentUsers.rootUserIdl;
			List<mch_depot_info> depotList = GodmchManageCallService
                    .SelectDepotByMchId(vipRootUserId);
    
			sqAddProductBean = initAddProduct(vipRootUserId, vipRootUserName, true);
			sqAddProductBean.setDepot_name(depotList.get(0).getDepotTitle());
//			Integer depotid=depotList.get(0).getDepotId();
			// 商户商品编码
			sqAddProductBean.getCatalog_list().forEach(c -> {
				String sku1 = TestDataManager.getRandomNum(6);
				c.setSku_id(sku1);
				c.setOuter_sku_id(null);
				//设置了专柜价格没写币种会报错
				c.setCounter_price(null);
			});
			sqAddProductBean.setProduct_param("{\"类目\":\"运动鞋\"}");
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper.selectApplicationBySellerId((long) vipRootUserId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id).get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil().beanToGSONString(sqAddProductBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq, AesUtil.decrypt(app_secret)));

			String url = String.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.product.add", app_id);
			shenqiAddProductCall.setUrl(url);

			shenqiAddProductCall.setData(openapiReq);
			shenqiAddProductCall.callService();

			JSONObject retBean = new JSONObject(shenqiAddProductCall.getReturnData());

			Logger.verifyEquals("0000", shenqiAddProductCall.getCode(), "验证Code");

			String productId = retBean.getJSONObject("content").getString("product_id");

			Thread.sleep(2000);

			// 验证数据库
//			checkAddAgentProduct(productId, sqAddProductBean, false);
			Map<String, Object> pmap = ipm.selectAgentProductsByProdId(productId);
			Logger.debug(pmap.toString());
			Logger.verifyEquals(sqAddProductBean.getProduct_param(),pmap.get("ProductParam").toString(), "验证ProductParam");
//			verifyMongoCurMq(productId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({ P1.class })
	@TestCase
	public void Tc_sqAddProduct_006() {
		Logger.start(true, "添加神器一品多码商品");
		try {

			sqAddProductBean = initAddProduct((int) multiCDFCodeGoodsOwnerId, vipRootUserName, true);

			// 商户商品编码
			sqAddProductBean.getCatalog_list().forEach(c -> {
				String sku1 = TestDataManager.getRandomNum(6);
				c.setSku_id(sku1);
				c.setOuter_sku_id(null);
				//设置了专柜价格没写币种会报错
				c.setCounter_price(null);
			});
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper.selectApplicationBySellerId((long) multiCDFCodeGoodsOwnerId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id).get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil().beanToGSONString(sqAddProductBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq, AesUtil.decrypt(app_secret)));

			String url = String.format("http://apigateway.shop2cn.com/apigateway/v1?app_id=%s&method=sq.product.add", app_id);
			shenqiAddProductCall.setUrl(url);

			shenqiAddProductCall.setData(openapiReq);
			shenqiAddProductCall.callService();

			JSONObject retBean = new JSONObject(shenqiAddProductCall.getReturnData());

			Logger.verifyEquals("0000", shenqiAddProductCall.getCode(), "验证Code");

			String productId = retBean.getJSONObject("content").getString("product_id");

			Thread.sleep(2000);

			// 验证数据库
			checkAddAgentProduct(productId, sqAddProductBean, false);
			verifyMongoCurMq(productId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	public static void setSkuForAddProduct(List<String> skuList, JSONObject addProdRequest) throws JSONException {
		JSONArray catalogAry = addProdRequest.getJSONObject("Product").getJSONArray("Catalogs");
		int minNum = Math.min(skuList.size(), catalogAry.length());
		for (int i = 0; i < minNum; i++) {
			catalogAry.getJSONObject(i).put("SKU", skuList.get(i));
		}
	}

	public static List<String> generateSKUList(int num) {
		List<String> skuList = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			skuList.add("SKU" + TestDataManager.getRandomIntNum(10));
		}
		return skuList;
	}

	public static Map<String, Object> generateSKUStock(List<String> skuList) {
		Map<String, Object> retMap = new HashMap<>();
		skuList.forEach(ele -> {
			int stock = TestDataManager.getRandomIntNum(2);
			retMap.put(ele, stock);
			Logger.comment("SKU: " + ele + ", stock: " + stock);
		});
		return retMap;
	}

	public static void checkStockBySku(JSONArray skuResults, Map<String, Object> skuIdandStockMap) throws Exception {
		YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();

		for (String skuId : skuIdandStockMap.keySet()) {
			// 返回报文检查
			boolean isFoundInRet = false;
			for (int j = 0; j < skuResults.length(); j++) {
				if (skuResults.getJSONObject(j).getString("sku_id").equals(skuId)) {
					Logger.verifyEquals(true, skuResults.getJSONObject(j).getBoolean("success"), "ExecSuccess 返回报文检查");

					isFoundInRet = true;
					break;
				}
			}
			Logger.verifyEquals(true, isFoundInRet, "SKU:" + skuId + ",在返回报文中是否存在");

			// 期待库存
			int tgtStock = Integer.parseInt(skuIdandStockMap.get(skuId).toString());

			YmtCatalogsI catalog = ymtCatalogsIWapper.selectCatalogsByCatalogId(skuId);

			String productId = catalog.getsProductId();
			String catalogId = catalog.getsCatalogId();
			int actStockInSql = Integer.parseInt(catalog.getiNum().toString());

			// sql
			Logger.verifyEquals(tgtStock, actStockInSql, "sql中库存检查 catalogId:" + catalogId);

			// mongo
			if (YmtMongoDriverFactroy.isNewMongoCheck()) {
				ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
				Map<String, Object> dataInMgo = productDetailModelWapper.getProductId(productId);
				JSONArray catalogAry = new JSONArray(dataInMgo.get("CatalogList").toString());

				boolean isFound = false;
				for (int i = 0; i < catalogAry.length(); i++) {
					JSONObject catalogBean = catalogAry.getJSONObject(i);
					if (catalogBean.getString("CatalogId").equals(catalogId)) {
						Logger.verifyEquals(skuId, catalogBean.getString("SKU"), "Mongo中sku检查 catalogId:" + catalogId + ", sku:" + skuId);

						JSONArray stockList = catalogBean.getJSONArray("StockList");
						for (int k = 0; k < stockList.length(); k++) {
							if (stockList.getJSONObject(k).getInt("StockType") == 0) {
								Logger.verifyEquals(tgtStock, stockList.getJSONObject(k).getInt("Stock"), "Mongo中库存检查 catalogId:" + catalogId + ", sku:" + skuId);
							}
						}

						isFound = true;
						break;
					}
				}

				Logger.verifyEquals(true, isFound, "scatalogId:" + catalogId + ", sku:" + skuId + ", 应该在mongo库中存在");
			}
			;

			// java mongo
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
				CatalogsWapper catalogsWapper = new CatalogsWapper();
				Map<String, Object> dataInMgo = catalogsWapper.getByCatalogId(catalogId);
				int actStockInMgo = Integer.parseInt(dataInMgo.get("stock").toString());
				Logger.verifyEquals(tgtStock, actStockInMgo, "Java Mongo中库存检查 catalogId:" + catalogId);
			}
		}
	}
}